var express = require("express");
var router = express.Router();
var Users = require("../models/users.js");

require("./../util/util")

/* GET users listing. */
router.get("/", function (req, res, next) {
  res.send("respond with a resource");
});


// router.post('/login', function (req, res) {
//   const name = req.body.userName;
//   const password = req.body.userPwd;
//   Users.find({
//     userName: name
//   }, function (err, users) {
//     if (users.length === 0) {
//       res.send({
//         isSuccess: false,
//         message: '该用户不存在'
//       });
//     } else if (users[0].userPwd === password) {
//       res.send({
//         isSuccess: true,
//         message: '登录成功'
//       });
//     } else if (users[0].userPwd !== password) {
//       res.send({
//         isSuccess: false,
//         message: '密码不正确，请重新输入'
//       });
//     }
//   });
// });
router.post("/login", function (req, res, next) {
  var param = {
    userName: req.body.userName,
    userPwd: req.body.userPwd
  };
  Users.findOne(param, function (err, doc) {
    if (err) {
      res.json({
        status: "1",
        msg: err.message
      })
      return
    } else {
      if (!doc) {
        res.json({
          status: "1",
          msg: "error",
          result: ""
        })
      } else {
        doc = {
          userId: doc.userId,
          userName: doc.userName
        }
        res.cookie("userId", JSON.stringify(doc), {
          path: "/",
          maxAge: 7 * 24 * 3600 * 1000
        })
        res.json({
          status: "0",
          msg: "success",
          result: {
            userName: doc.userName
          }
        })
      }
    }
  });
});

//登出
router.post("/logout", function (req, res, next) {
  res.cookie("userId", "", {
    path: "/",
    maxAge: -1
  })
  res.json({
    status: "0",
    msg: "",
    result: ""
  })
})

//检查cookies
router.get("/checkLogin", function (req, res, next) {
  // console.log(JSON.parse(req.cookies.userId).userId)
  if (req.cookies.userId) {
    res.json({
      status: "0",
      msg: "",
      result: JSON.parse(req.cookies.userId).userName
    })
  } else {
    res.json({
      status: "1",
      msg: "当前未登录",
      result: ""
    })
  }
})

//购物车数据
router.get("/cartList", function (req, res, next) {
  var userId = JSON.parse(req.cookies.userId).userId
  Users.findOne({
    userId: userId
  }, function (err, doc) {
    if (err) {
      res.json({
        status: "1",
        msg: err.message,
        result: ""
      })
    } else {
      if (doc) {
        res.json({
          status: "0",
          msg: "",
          result: doc.cartList
        })
      }
    }
  })
})

//购物车数据删除
router.post("/cartDel", function (req, res, next) {
  var userId = JSON.parse(req.cookies.userId).userId;
  var productId = req.body.productId;
  Users.update({
    userId: userId
  }, {
    $pull: {
      "cartList": {
        "productId": productId
      }
    }
  }, function (err, doc) {
    if (err) {
      res.json({
        status: "1",
        msg: err.message,
        result: ""
      })
    } else {
      if (doc) {
        res.json({
          status: "0",
          msg: "",
          result: "删除成功"
        })
      }
    }
  })
})

//数据库商品数据编辑
router.post("/editCart", function (req, res, next) {
  var userId = JSON.parse(req.cookies.userId).userId;
  var productId = req.body.productId;
  var productNum = req.body.productNum;
  var checked = req.body.checked;
  Users.update({
    "userId": userId,
    "cartList.productId": productId
  }, {
    "cartList.$.productNum": productNum,
    "cartList.$.checked": checked
  }, function (err, doc) {
    if (err) {
      res.json({
        status: "1",
        msg: err.message,
        result: ""
      })
    } else {
      if (doc) {
        res.json({
          status: "0",
          msg: "",
          result: "修改成功"
        })
      }
    }
  })
})

//购物车的全选
router.post("/editCheckAll", function (req, res, next) {
  var userId = JSON.parse(req.cookies.userId).userId;
  var checkAll = req.body.checkAll ? "1" : "0";
  Users.findOne({
    userId: userId
  }, (err, user) => {
    if (err) {
      res.json({
        status: "1",
        msg: err.message,
        result: ""
      })
    } else {
      if (user) {
        user.cartList.forEach(element => {
          element.checked = checkAll
        });
        user.save((err1, doc1) => {
          if (err1) {
            res.json({
              status: "1",
              msg: err1.message,
              result: ""
            })
          } else {
            res.json({
              status: "0",
              msg: "",
              result: "success"
            })
          }
        })

      }
    }
  })

})

//地址
router.get("/addressList", function (req, res, next) {
  var userId = JSON.parse(req.cookies.userId).userId
  Users.findOne({
    userId: userId
  }, function (err, doc) {
    if (err) {
      res.json({
        status: "1",
        msg: err.message,
        result: ""
      })
    } else {
      if (doc) {
        res.json({
          status: "0",
          msg: "",
          result: doc.addressList
        })
      }
    }
  })
})

//设置默认地址
router.post("/setDefault", (req, res, next) => {
  var userId = JSON.parse(req.cookies.userId).userId;
  var addressId = req.body.addressId;
  Users.findOne({
    userId: userId
  }, (err, doc) => {
    if (err) {
      res.json({
        status: "1",
        msg: err.message,
        result: ""
      })
    } else {
      var addressList = doc.addressList;
      addressList.forEach((ele) => {
        if (ele.addressId == addressId) {
          ele.isDefault = true
        } else {
          ele.isDefault = false
        }
      });
      doc.save((err1, doc1) => {
        if (err1) {
          res.json({
            status: "1",
            msg: err.message,
            result: ""
          })
        } else {
          res.json({
            status: "0",
            msg: "",
            result: ""
          })
        }
      })
    }
  })
})

//添加新的地址
router.post('/addRess', function (req, res, next) {
  var userId = JSON.parse(req.cookies.userId).userId;
  var addressId = req.body.addressId;
  var userName = req.body.userName;
  var streetName = req.body.streetName;
  var postCode = req.body.postCode;
  var tel = req.body.tel;
  var isDefault = req.body.isDefault;

  Users.findOne({
    userId: userId
  }, function (err, doc) {
    if (err) {
      res.json({
        status: "1",
        msg: err.message,
        result: ""
      })
    } else {
      if (doc) {
        addInfo = {
          "addressId": addressId,
          "userName": userName,
          "streetName": streetName,
          "postCode": postCode,
          "tel": tel,
        }
        doc.addressList.push(addInfo);
        doc.save(function (err1, doc1) {
          if (err1) {
            res.json({
              status: "1",
              msg: err1.message,
              result: ""
            })
          } else {
            res.json({
              status: "0",
              msg: "",
              result: "success"
            })
          }
        })
      }
    }
  })
})

//地址删除
router.post("/addressDel", function (req, res, next) {
  var userId = JSON.parse(req.cookies.userId).userId;
  var addressId = req.body.addressId;
  Users.update({
    userId: userId
  }, {
    $pull: {
      "addressList": {
        "addressId": addressId
      }
    }
  }, function (err, doc) {
    if (err) {
      res.json({
        status: "1",
        msg: err.message,
        result: ""
      })
    } else {
      if (doc) {
        res.json({
          status: "0",
          msg: "",
          result: "删除成功"
        })
      }
    }
  })
});

//购物车商品成功
router.post("/successPay", (req, res, next) => {
  var userId = JSON.parse(req.cookies.userId).userId;
  var addressId = req.body.addressId;
  var orderTotal = req.body.orderTotal;
  Users.findOne({
    userId: userId
  }, function (err, doc) {
    if (err) {
      res.json({
        status: "1",
        msg: err.message,
        result: ""
      })
    } else {
      var address = '',
        goodsList = [];
      doc.addressList.forEach(item => {
        if (addressId == item.addressId) {
          address = item;
        }
      })
      //获取用户购物车购买的商品
      doc.cartList.filter(item => {
        if (item.checked == 1) {
          goodsList.push(item);
        }
      })
      var ff = "6217";
      var r1 = Math.floor(Math.random() * 10);
      var r2 = Math.floor(Math.random() * 10);
      var startDate = new Date().Format('yyyyMMddhhmmss');
      var creatDate = new Date().Format('yyyy-MM-dd hh: mm: ss');
      var orderId = ff + r1 + startDate + r2;
      var order = {
        orderId: orderId,
        orderTotal: orderTotal,
        addressInfo: address,
        goodsList: goodsList,
        orderStatus: "1"
      }
      doc.orderList.push(order)
      doc.save(function (err1, doc1) {
        if (err1) {
          res.json({
            status: "1",
            msg: err1.message,
            result: ""
          })
        } else {
          res.json({
            status: "0",
            msg: "",
            result: {
              orderId: order.orderId,
              orderTotal: order.orderTotal
            }
          })
        }
      })

    }
  })

});

//查找商品订单
router.get("/orderSuccess", function (req, res, next) {
  var userId = JSON.parse(req.cookies.userId).userId;
  var orderId = req.param("orderId");
  Users.findOne({
    userId: userId,
  }, function (err, doc) {
    if (err) {
      res.json({
        status: "1",
        msg: err.message,
        result: ""
      })
    } else {
      if (doc) {
        var orderTotal = 0;
        var orderList = doc.orderList;
        if (orderList.length > 0) {
          orderList.forEach(item => {
            if (orderId == item.orderId) {
              orderTotal = item.orderTotal
            }
          });
          if (orderTotal > 0) {
            res.json({
              status: "0",
              msg: "",
              result: {
                orderId: orderId,
                orderTotal: orderTotal
              }
            })
          } else {
            res.json({
              status: "10002",
              msg: "无此订单",
              result: ""
            })
          }
        }
      } else {
        res.json({
          status: "10001",
          msg: "暂无订单信息",
          result: ""
        })
      }
    }
  })
})

module.exports = router;
